#define _WINSOCK_DEPRECATED_NO_WARNINGS
#include <winsock2.h>
#include <iostream>
#include<string>
using namespace std;
#pragma comment(lib, "ws2_32.lib")

void InitWinsock()
{
	WSADATA wsaData;
	int wsOk = WSAStartup(MAKEWORD(2, 2), &wsaData);
	if (wsOk != 0)
	{
		printf("Can't Initialize winsock! Quitting\n");
		return;
	}
	printf("Initialize winsock.\n");
}

int main(int argc, char* argv[])
{
	SOCKET socketC;

	InitWinsock();
	struct sockaddr_in serverInfo;
	int len = sizeof(serverInfo);
	serverInfo.sin_family = AF_INET;
	serverInfo.sin_port = htons(8087);
	serverInfo.sin_addr.s_addr = inet_addr("127.0.0.1");

	// SOCK_STREAM use for TCP and SOCK_DGRAM for UDP
	socketC = socket(AF_INET, SOCK_DGRAM, 0);
	if (socketC == INVALID_SOCKET)
	{
		printf("Can't create a socket! Quitting\n");
		return -1;
	}
	printf("Socket  Created.\n");

	while (1)
	{
		char buffer[50], buffer1[50];
		ZeroMemory(buffer, sizeof(buffer));

		printf("Please input your message: ");
		cin >> buffer;
		if (strcmp(buffer, "exit") == 0)
			break;
		if (sendto(socketC, buffer, sizeof(buffer), 0, (sockaddr*)&serverInfo, len) != SOCKET_ERROR)
		{
			if (recvfrom(socketC, buffer1, sizeof(buffer1), 0, (sockaddr*)&serverInfo, &len))
			{
				printf("Receive response from server: %s\n", buffer1);
			}
		}
	}
	closesocket(socketC);
	return 0;
}